import { useEffect, useState } from 'react';
import { getPageMeta } from '@/services/request/meta';
import { MetaSorted } from 'schema-form';
import {  initialSchemaNoraml, initialSchemaSearch } from '@/components/schema-form-render/utils';

// import { useCacheData } from './with-list/use-events';


/**
 * 高阶列表页面，列表按钮事件注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerListTableEvent = (target: any, events: any, params: any) => {
    const { setLoading = () => {}, match } = params;
    Object.keys(events).forEach(hookName => {
        let old:any = null
        if (target[hookName]) {
           old = target[hookName];
        }
        target[hookName] = async (id: string, row: any, index: number) => {
            if (events && events[hookName]) {
                setLoading(true);

              //  const [searchCache] = useCacheData(match);
              //  params.searchCache = searchCache;

                const res: any = await events[hookName](id, row, params, index);
                if (res?.success) {
                    params.callback && params.callback(true);
                    setLoading(false);
                }
                old && old(id, row);
                setLoading(false);
            }
        }
    })
}


/**
 *
 * @param pageCode
 * @param type
 * @param eventMap
 * @returns
 */
export const useMetaInit = (pageCode:string, type: 'SEARCH' | 'DETAIL' | 'NORMAL' = 'SEARCH', eventMap: any = {}):[MetaSorted, any] => {
    const [configs, setConfigs] = useState<MetaSorted>({});
    useEffect(() => {
        getPageMeta(pageCode).then(async(res: any) => {
            if (res.success) {
                const sss: any = type === 'SEARCH' ? initialSchemaSearch(
                    res.result, '', false
                ): initialSchemaNoraml(res.result, false, type, eventMap);
                setConfigs(sss)
            }
        })
    }, [])
    return [configs, setConfigs]
}

/**
 * 高阶列表页面，普通按钮注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
 export const registerListButtonEvent = (target: any, events: any, params: any) => {
    const { setLoading = () => {}, match } = params;
    Object.keys(events).forEach(hookName => {
        let old:any = null
        if (target[hookName]) {
           old = target[hookName];
        }
        target[hookName] = async () => {
            if (events && events[hookName]) {
                setLoading(true);

             //   const [searchCache] = useCacheData(match);
              //  params.searchCache = searchCache;

                const res: any = await events[hookName](params);
                console.log('res', res);
                setLoading(false);
                if (res?.success) {
                }
                old && old();
            }
        }
    })
}
